package com.gowants.pems.config;


import com.gowants.pems.model.SysUser;
import com.gowants.pems.service.SysUserService;
import com.gowants.pems.util.MD5;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;


public class MyShiroRealm extends AuthorizingRealm {
	private Logger logger = Logger.getLogger(MyShiroRealm.class);
    @Resource
    private SysUserService userInfoService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals){
//        // 权限信息对象info,用来存放查出的用户的所有的角色（role）及权限（permission）
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        System.out.println("SessionId3="+SecurityUtils.getSubject().getSession().getId());
        // 用户的角色集合
        Set<String> roles = new HashSet<>();
//        roles.add(user.getRoleList().get(0).getRole());
        authorizationInfo.setRoles(roles);
        return authorizationInfo;
    }

    /*主要是用来进行身份认证的，也就是说验证用户输入的账号和密码是否正确。*/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
            throws AuthenticationException {
    	 UsernamePasswordToken userToken = (UsernamePasswordToken) token;
         String userName = userToken.getUsername();
       
         // 数据库中查询用户
         SysUser user = userInfoService.selectUserName(userName);
         logger.debug("ShiroMethod AuthenticationInfo >>> user:[ loginName:" + user.getUserName() + "]");

         // 密码比对
         return new SimpleAuthenticationInfo(user, MD5.md5(user.getPwd()), "");
//         return new SimpleAuthenticationInfo(token,userToken.getPassword(),userName);
    }

}